<?php
/**
 * Created by PhpStorm.
<<<<<<< HEAD
 * User: admin
 * Date: 2019/5/20
 * Time: 11:14
 */

namespace app\index\controller;
use think\Controller;
use think\Db;
use think\facade\Session;

class Base extends Controller
{
    public function initialize(){
//        Session::set('openid',null);
        if(empty(Session::get('openid'))){
            $get=input('get.');
            $whereAB['wx_id']=1;
            $wechatRes=Db::name('wechatconfig')->where($whereAB)->find();
            $appid=$wechatRes['appid'];
            $appsecret=$wechatRes['appsecret'];
            if (!isset($get['code'])) {
                //生成state 通过session验证
                $state = self::getState(25, 32);
                Session::set('state',$state);

//                $redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                $redirect_uri = urlencode ('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
//                dump($redirect_uri);die();
                $getCodeUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='. $appid .'&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . $state . '#wechat_redirect';
                $this->redirect($getCodeUrl);
            }else{
                if ($get['state'] === Session::get('state')){
                    $getAccessTokenUrl ='https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $get['code'] . '&grant_type=authorization_code';
                    $data = json_decode(self::curlRequest($getAccessTokenUrl), true);
                    if (isset($data['openid'])) {
                        //获取用户信息
                        $getUserInfoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['access_token'] . '&openid=' . $data['openid'] . '&lang=zh_CN';
                        $user_info = json_decode(self::curlRequest($getUserInfoUrl), true);
                        Session::set('openid',$user_info['openid']);
                        Session::set('nickname',$user_info['nickname']);
                        Session::set('headimgurl',$user_info['headimgurl']);

                        //判断数据库是否有用户
                        $member=Db::name('member')->where('openid',Session::get('openid'))->find();
                        $dataaa=[
                            'openid'=>$user_info['openid'],
                            'nickname'=>$user_info['nickname'],
                            'headimgurl'=>$user_info['headimgurl'],
                            'sex'=>$user_info['sex'],
                            'country'=>$user_info['country'],
                            'province'=>$user_info['province'],
                            'city'=>$user_info['city']
                        ];
                        if(empty($member)){
                            $dataaa['create_time']=time();
                            Db::name('member')->insert($dataaa);
                        }else{
                            Db::name('member')->where('openid',Session::get('openid'))->update($dataaa);
                        }
                    }
                }
            }
        }
        $user=Db::name('member')->where('openid',Session::get('openid'))->find();
        Session::set('user_id',$user['id']);
    }
    private static function getState($minLength, $maxLength)
    {
        $length = mt_rand($minLength, $maxLength);
        $letters = '1234567890bcdfghjklmnpqrstvwxyz';
        $vowels = 'aeiou';
        $code = '';
        for ($i = 0; $i < $length; ++$i) {
            if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
                $code .= $vowels[mt_rand(0, 4)];
            } else {
                $code .= $letters[mt_rand(0, 20)];
            }
        }
        return $code;
    }
    public function curlRequest($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    //随机数
    public function randomStr(){
        $arr = array_merge(range(0,9),range('A','Z'));
        $str = '';
        $arr_len = count($arr);
        for($i = 0;$i < 8;$i++){
            $rand = mt_rand(0,$arr_len-1);
            $str.=$arr[$rand];
        }
        return $str;
    }


}